﻿@inject DocService DocService
@inherits NextTickComponentBase
@implements INavDrawer
@inject IJSRuntime JSRuntime
@inject I18n I18n

<MNavigationDrawer Value="Value"
                   ValueChanged="ValueChanged"
                   Id="@ElementId"
                   Class="default-nav"
                   Right="RTL"
                   App
                   Width="300"
                   Clipped>
    <ChildContent>
        <CascadingValue Value="this" IsFixed>
            <DefaultList Class="doc-list-nav"
                         Routable
                         Items="Navs">
                <GroupContent>
                    @if (context == "ui-components")
                    {
                        <div class="d-flex align-center justify-space-between"
                             style="margin-left: 72px; margin-right: 16px; margin-bottom: 8px;">
                            <span class="text--secondary text-caption">@I18n.T("nav-component-group-by-type")</span>
                            <NavComponentsTypeSwitch Config="@Config" ConfigChanged="@ConfigChanged" Dense/>
                        </div>
                    }
                </GroupContent>
            </DefaultList>
        </CascadingValue>
    </ChildContent>
    <AppendContent>
        <NavDrawerAppend/>
    </AppendContent>
</MNavigationDrawer>

@code {

    [CascadingParameter(Name = "Culture")]
    public string Culture { get; set; } = null!;

    [CascadingParameter(Name = "project")]
    public string? Project { get; set; }

    [Parameter]
    public bool RTL { get; set; }

    [Parameter]
    public bool? Value { get; set; }

    [Parameter]
    public EventCallback<bool?> ValueChanged { get; set; }

    [Parameter]
    public Config? Config { get; set; }

    [Parameter]
    public EventCallback<Config?> ConfigChanged { get; set; }

    private string? _lastProject;
    private List<NavItem> Navs { get; set; } = new();

    public string ElementId => "nav-drawer";

    protected override async Task OnParametersSetAsync()
    {
        await base.OnParametersSetAsync();

        if (_lastProject != Project)
        {
            _lastProject = Project;
            if (Project is null)
            {
                Navs = new();
                return;
            }

            Navs = await DocService.ReadNavsAsync(Project);

            _ = Task.Run(async () =>
            {
                await Task.Delay(500);
                await ScrollIntoView("#nav-drawer");
            });
        }
    }

    private async Task ScrollIntoView(string ancestorSelector)
    {
        var target = $"{ancestorSelector} .m-list-item--active:not(.m-list-group__header)";
        var container = $"{ancestorSelector} .m-navigation-drawer__content";
        await JSRuntime.InvokeVoidAsync(
            JsInteropConstants.ScrollToTarget,
            target,
            container,
            Config?.NavComponentsGroupByType is true ? 48 : 0,
            "smooth");
    }

}
